package com.kun.kunkunmall.gateway.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.kun.common.exception.BizCodeEnum;
import com.kun.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class SentinelGateWayConfig {

    /**
     * 自定义网关流控回调
     */
    public SentinelGateWayConfig(){
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                R error = R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.USER_EXIST_EXCEPTION.getMsg());
                String jsonStr = JSONUtil.toJsonStr(error);
                Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(error), String.class);
                return body;
            }
        });
    }

}
